package com.commerceerp.system.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * Created by Administrator on 2018/5/12.
 */
public class FileUtil {

    //获取文件后缀名
    public static String getType(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    //改文件后缀名
    public static String changeType(String fileName, String type) {

        return fileName.substring(0, fileName.lastIndexOf(".") + 1) + type;
    }

    /**
     * 上传文件
     * @param file 文件
     * @param path 上传目录
     * @param resumeurl 文件名
     * @throws Exception
     */
    public static void addFile(MultipartFile file, String path, String resumeurl) throws Exception{
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(path + new File(resumeurl)));
        out.write(file.getBytes());
        out.flush();
        out.close();
    }

    //将文件从path1转移到path2
    public static void move(String path1,String path2) throws FileNotFoundException, IOException {
        FileInputStream fis = new FileInputStream(path1);
        FileOutputStream fos = new FileOutputStream(path2);

        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fis.close();
        fos.close();
    }

    //删除文件
    public static void delFile(String path) {
        File file = new File(path);
        if (file.isFile()) {
            file.delete();
        }
    }

    public static void main(String[] args) {
        try {
            move("static/img/154087804468299.jpg","static/discard/154087804468299.jpg");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
